<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 1000px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNo">
        <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
      </el-form-item>
      <el-form-item label="乙方" prop="partyB">
        <el-select
          v-model="formData.partyB"
          clearable
          filterable
          placeholder="请选择供应商"
          class="!w-1/1"
          :filter-method="handleSupplierFilterMethod"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <div class="flex">
        <el-form-item label="签订时间" prop="signingDate">
          <el-date-picker
            v-model="formData.signingDate"
            type="date"
            value-format="x"
            placeholder="选择签订时间"
          />
        </el-form-item>
        <el-form-item label="终止日期" prop="expirationDate">
          <el-date-picker
            v-model="formData.expirationDate"
            type="date"
            value-format="x"
            placeholder="选择终止日期"
          />
        </el-form-item>
      </div>
      <el-form-item label="生效日期" prop="effectiveDate">
        <el-date-picker
          v-model="formData.effectiveDate"
          type="date"
          value-format="x"
          placeholder="选择生效日期"
        />
      </el-form-item>
      <el-form-item label="合同责任人" prop="contractPerson">
        <el-input v-model="formData.contractPerson" placeholder="请输入合同责任人" />
      </el-form-item>
      <el-form-item label="摘要内容" prop="contractSummary">
        <el-input v-model="formData.contractSummary" placeholder="请输入摘要内容" type="textarea" />
      </el-form-item>
      <ContentWrap>
        <el-tabs class="-mt-15px -mb-10px" v-model="subTabsName">
          <el-tab-pane label="物料价格关联区块" name="item">
            <!-- 合并子组件内容开始 -->
            <el-form
              ref="itemFormRef"
              :model="formData.items"
              :rules="itemFormRules"
              v-loading="itemFormLoading"
              label-width="0px"
              :inline-message="true"
            >
              <el-table :data="formData.items" show-summary class="-mt-10px">
                <el-table-column label="序号" type="index" align="center" width="60" />
                <el-table-column label="餐谱名称">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="`${$index}.productId`"
                      :rules="itemFormRules.productId"
                      class="mb-0px!"
                    >
                      <!-- @change="onChangeProduct($event, row)" -->
                      <el-select
                        v-model="row.productId"
                        clearable
                        filterable
                        placeholder="请选择餐谱"
                        :filter-method="handleProductFilterMethod"
                      >
                        <el-option
                          v-for="item in productList"
                          :key="item.id"
                          :label="item.recipeName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="价格(元)" align="center" prop="price" min-width="160">
                  <template #default="{ row }">
                    <el-input
                      v-model="row.price"
                      placeholder="请输入价格"
                      style="width: 140px"
                      type="number"
                    />
                  </template>
                </el-table-column>

                <el-table-column label="生效日期">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="`${$index}.productEffectiveDate`"
                      :rules="itemFormRules.productEffectiveDate"
                      class="mb-0px!"
                    >
                      <el-date-picker
                        v-model="row.productEffectiveDate"
                        type="date"
                        value-format="x"
                        placeholder="选择生效日期"
                        class="!w-160px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="终止日期">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="`${$index}.productExpirationDate`"
                      :rules="itemFormRules.productExpirationDate"
                      class="mb-0px!"
                    >
                      <el-date-picker
                        v-model="row.productExpirationDate"
                        type="date"
                        value-format="x"
                        placeholder="选择终止日期"
                        class="!w-160px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" min-width="60" fixed="right">
                  <template #default="{ $index }">
                    <el-button @click="handleDeleteItem($index)" link type="primary"
                      >删除此条</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <el-row justify="center" class="mt-3">
              <el-button @click="handleAddItem" round>+ 添加物料价格关联</el-button>
            </el-row>
            <!-- 合并子组件内容结束 -->
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-form-item label="文件" prop="contractFile">
        <UploadFile v-model="formData.contractFile" :fileType="['pdf']" />
      </el-form-item>
      <el-form-item label="版本备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入版本备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MarketContractApi, MarketContractVO } from '@/api/erp/marketcontract'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import { RecipeApi, RecipeVO } from '@/api/pplan/recipe'
import { erpCountFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'

/** 市场管理合同信息 表单 */
defineOptions({ name: 'MarketContractForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  partyB: undefined,
  id: undefined,
  contractName: undefined,
  contractNo: undefined,
  partyB: undefined,
  signingDate: undefined,
  expirationDate: undefined,
  effectiveDate: undefined,
  contractSummary: undefined,
  contractPerson: undefined,
  contractFile: undefined,
  items: [],
  remark: undefined
})

const formRef = ref() // 表单 Ref
const subTabsName = ref('item')

// 子表单相关变量（原MarketContractItemForm内容）
const itemFormRef = ref<any>(null) // 子表单 Ref
const itemFormLoading = ref(false) // 子表单的加载中
const productList = ref<RecipeVO[]>([]) // 显示在下拉框中的产品列表
const productAllList = ref<RecipeVO[]>([]) // 完整的产品列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const result = await MarketContractApi.getMarketContract(id)
      formData.value = {
        ...result,
        items: result.items || [] // 确保items数组存在
      }
      // 确保已选择的产品都在产品列表中
      await ensureSelectedProductsInList()
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时默认添加一个空的物料价格关联
    formData.value.items = []
    await handleAddItem()
  }
  // 加载供应商列表和产品列表
  await Promise.all([handleSupplierFilterMethod(), loadAllProducts()])
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const handleSupplierFilterMethod = async (query?: string) => {
  console.log('filtering suppliers with query:', query)
  const data = await SupplierApi.getSupplierSimpleList()
  if (!query) {
    supplierList.value = data.slice(0, 200)
    return supplierList.value
  }
  supplierList.value = data.filter((d) => d.name.toLowerCase().includes(query.toLowerCase()))
  return supplierList.value
}

/** 处理物料价格关联变化 */
const handleItemsChange = () => {
  // 触发items字段的验证
  formRef.value?.validateField('items')
}

/** 验证签订时间 */
const validateSigningDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }

  const signingDate = new Date(Number(value))
  const expirationDate = formData.value.expirationDate
    ? new Date(Number(formData.value.expirationDate))
    : null

  if (expirationDate && signingDate > expirationDate) {
    return callback(new Error('签订时间不能在终止日期之后'))
  }

  callback()
}

/** 验证终止日期 */
const validateExpirationDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }

  const expirationDate = new Date(Number(value))
  const signingDate = formData.value.signingDate
    ? new Date(Number(formData.value.signingDate))
    : null
  const effectiveDate = formData.value.effectiveDate
    ? new Date(Number(formData.value.effectiveDate))
    : null

  if (signingDate && expirationDate < signingDate) {
    return callback(new Error('终止日期不能在签订时间之前'))
  }

  if (effectiveDate && expirationDate < effectiveDate) {
    return callback(new Error('终止日期不能在生效日期之前'))
  }

  callback()
}

/** 验证生效日期 */
const validateEffectiveDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }

  const effectiveDate = new Date(Number(value))
  const signingDate = formData.value.signingDate
    ? new Date(Number(formData.value.signingDate))
    : null
  const expirationDate = formData.value.expirationDate
    ? new Date(Number(formData.value.expirationDate))
    : null

  if (signingDate && effectiveDate < signingDate) {
    return callback(new Error('生效日期不能在签订时间之前'))
  }

  if (expirationDate && effectiveDate > expirationDate) {
    return callback(new Error('生效日期不能在终止日期之后'))
  }

  callback()
}

/** 验证物料价格关联 */
const validateItems = (rule: any, value: any, callback: any) => {
  if (!value || value.length === 0) {
    return callback(new Error('物料价格关联区块内容不能为空'))
  }

  // 验证子表单
  if (itemFormRef.value) {
    itemFormRef.value
      .validate()
      .then(() => {
        callback()
      })
      .catch((error: any) => {
        callback(new Error('物料价格关联区块存在未填写的必填项'))
      })
  } else {
    callback()
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    // 校验主表单
    await formRef.value.validate()

    // 校验子表单
    if (itemFormRef.value) {
      await itemFormRef.value.validate()
    }

    // 提交请求
    formLoading.value = true
    const data = formData.value as unknown as MarketContractVO
    if (formType.value === 'create') {
      await MarketContractApi.createMarketContract(data)
      message.success(t('common.createSuccess'))
    } else {
      await MarketContractApi.updateMarketContract(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    formLoading.value = false
  }
}

/* 表单校验 */
const formRules = reactive({
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  partyB: [{ required: true, message: '乙方名称（供应商）不能为空', trigger: 'change' }],
  signingDate: [
    { required: true, message: '签订时间不能为空', trigger: 'blur' },
    { validator: validateSigningDate, trigger: 'blur' }
  ],
  expirationDate: [
    { required: true, message: '终止日期不能为空', trigger: 'blur' },
    { validator: validateExpirationDate, trigger: 'blur' }
  ],
  effectiveDate: [
    { required: true, message: '生效日期不能为空', trigger: 'blur' },
    { validator: validateEffectiveDate, trigger: 'blur' }
  ],
  contractPerson: [{ required: true, message: '合同责任人不能为空', trigger: 'blur' }],
  items: [{ validator: validateItems, trigger: 'change' }]
})

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractName: undefined,
    contractNo: undefined,
    partyB: undefined,
    signingDate: undefined,
    expirationDate: undefined,
    effectiveDate: undefined,
    contractSummary: undefined,
    contractPerson: undefined,
    contractFile: undefined,
    items: [],
    remark: undefined
  }
  formRef.value?.resetFields()
}

// 以下是原MarketContractItemForm组件的内容
/** 加载所有产品 */
const loadAllProducts = async () => {
  try {
    const res = await RecipeApi.getRecipeSimpleList()
    productAllList.value = res.list || []
    console.log('Loaded products:', productAllList.value)
    return res
  } catch (error) {
    console.error('Failed to load products:', error)
    productAllList.value = []
    return { list: [] }
  }
}

/** 确保已选择的产品都在下拉列表中 */
const ensureSelectedProductsInList = async () => {
  if (productAllList.value.length === 0) {
    // 如果还没有加载完整列表，先加载
    await loadAllProducts()
  }

  // 获取所有已选择的产品ID
  const selectedProductIds = formData.value.items.map((item) => item.productId).filter(Boolean)

  // 检查这些产品是否都在当前显示的列表中
  selectedProductIds.forEach((productId) => {
    const existsInList = productList.value.some((item) => item.id === productId)
    if (!existsInList) {
      // 如果不在，从完整列表中找到并添加
      const product = productAllList.value.find((item) => item.id === productId)
      if (product) {
        productList.value.push(product)
      }
    }
  })
}

/** 处理产品过滤方法 */
const handleProductFilterMethod = async (query?: string) => {
  // 确保已加载所有产品
  if (productAllList.value.length === 0) {
    await loadAllProducts()
  }

  // 先获取所有已选择的产品，确保它们会被包含在结果中
  const selectedProducts = formData.value.items
    .map((item) => productAllList.value.find((p) => p.id === item.productId))
    .filter(Boolean)

  if (!query) {
    // 如果没有查询条件，显示前200条加上已选择的产品
    const topProducts = [...productAllList.value].slice(0, 200)
    // 合并并去重
    productList.value = Array.from(
      new Map([...topProducts, ...selectedProducts].map((item) => [item.id, item])).values()
    )
  } else {
    // 有查询条件时，显示匹配的产品加上已选择的产品
    const filteredProducts = productAllList.value.filter((d) =>
      d.recipeName.toLowerCase().includes(query.toLowerCase())
    )
    // 合并并去重
    productList.value = Array.from(
      new Map([...filteredProducts, ...selectedProducts].map((item) => [item.id, item])).values()
    )
  }

  return productList.value
}

/** 验证产品生效日期 */
const validateProductEffectiveDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }

  // 检查rule.model是否存在
  if (!rule.model) {
    return callback()
  }

  const effectiveDate = new Date(Number(value))
  const expirationDate = rule.model.productExpirationDate
    ? new Date(Number(rule.model.productExpirationDate))
    : null

  if (expirationDate && effectiveDate > expirationDate) {
    return callback(new Error('生效日期不能在终止日期之后'))
  }

  callback()
}

/** 验证产品终止日期 */
const validateProductExpirationDate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }

  // 检查rule.model是否存在
  if (!rule.model) {
    return callback()
  }

  const expirationDate = new Date(Number(value))
  const effectiveDate = rule.model.productEffectiveDate
    ? new Date(Number(rule.model.productEffectiveDate))
    : null

  if (effectiveDate && expirationDate < effectiveDate) {
    return callback(new Error('终止日期不能在生效日期之前'))
  }

  callback()
}

const itemFormRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  productExpirationDate: [
    { required: true, message: '终止日期不能为空', trigger: 'blur' },
    { validator: validateProductExpirationDate, trigger: 'blur' }
  ],
  productEffectiveDate: [
    { required: true, message: '生效日期不能为空', trigger: 'blur' },
    { validator: validateProductEffectiveDate, trigger: 'blur' }
  ]
})

/** 新增物料价格关联 */
const handleAddItem = async () => {
  const row = {
    id: undefined,
    productId: undefined,
    productExpirationDate: undefined,
    productEffectiveDate: undefined,
    price: undefined
  }

  formData.value.items.push(row)
  console.log('Added new item row:', row)
  console.log('Current items:', formData.value.items)

  // 使用nextTick确保DOM更新完成
  await nextTick()

  // 触发验证
  handleItemsChange()
}

/** 删除物料价格关联 */
const handleDeleteItem = async (index: number) => {
  formData.value.items.splice(index, 1)

  // 使用nextTick确保DOM更新完成
  await nextTick()

  // 触发验证
  handleItemsChange()
}

/** 处理产品变更 */
// const onChangeProduct = async (productId, row) => {
//   const product = productAllList.value.find((item) => item.id === productId)
//   if (product) {
//     row.price = product.purchasePrice
//   }

//   // 使用nextTick确保DOM更新完成
//   await nextTick()

//   // 触发验证
//   handleItemsChange()
// }

// 处理单位回显
const productUnitNameFun = (productId: any) => {
  const product = productAllList.value.find((item) => item.id === productId)
  return product ? product.purchasePrice : ''
}

/** 监听items变化，自动触发验证 */
watch(
  () => formData.value.items,
  (newValue) => {
    handleItemsChange()
  },
  { deep: true }
)
</script>
